package com.example.docking.service.impl;

import com.example.docking.dao.jindie.GenericDataItem;
import com.example.docking.dao.jindie.ResponseData;
import com.example.docking.dao.jindie.response.StoreDao;
import com.example.docking.service.StoreService;
import com.example.docking.util.Constants;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.smecloud.apigw.model.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class StoreServiceImpl implements StoreService {
    private static final Logger logger = LoggerFactory.getLogger(EmpServiceImpl.class);

    @Override
    public List<StoreDao> selectList() {
        Gson gson = new Gson();
        // 设置分页参数
        int page = 1; // 初始页码
        int pageSize = 10; // 每页记录数
        HashMap<String, String> map = new HashMap<>();
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        List<StoreDao> allData = null;
        ApiResult DataResult = null;
        DataServiceImpl Service = new DataServiceImpl();
        // 调用分页查询方法获取职员数据
        try {
            DataResult = Service.SelectDataList(Constants.STORE, map, "");

            Type DataType = new TypeToken<ResponseData<GenericDataItem<StoreDao>>>() {
            }.getType();
            ResponseData<GenericDataItem<StoreDao>> responseData = gson.fromJson(DataResult.getBody(), DataType);
            logger.info("查询返回code:" + responseData.getErrcode());
            logger.info("查询返回description:" + responseData.getDescription());
            GenericDataItem<StoreDao> genericDataItem = responseData.getData();
            // 解析分页信息
            String count = genericDataItem.getCount();
            int countNum = Integer.valueOf(count);
            int Pagesum = pageSize;
            List<StoreDao> Data = genericDataItem.getRows();

            allData = new ArrayList<>(Data);
            // 如果不是最后一页，继续获取下一页数据
            while (Pagesum < countNum) {
                page++;
                map.put("page", String.valueOf(page));
                DataResult = Service.SelectDataList(Constants.STORE, map, "");
                responseData = gson.fromJson(DataResult.getBody(), DataType);
                genericDataItem = responseData.getData();
                Data = genericDataItem.getRows();
                allData.addAll(Data);
                Pagesum = (pageSize * page);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return allData;
    }

    public static void main(String[] args) {
        StoreServiceImpl service = new StoreServiceImpl();
        List<StoreDao> data = service.selectList();
        System.out.println(data);
    }
}
